﻿
Imports System.IO

Public Class fifoMemoryStream
    Inherits Stream

    Private _buff As bytes = Nothing
    Private _pos As Int64

    Public Overrides ReadOnly Property CanRead As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides ReadOnly Property CanSeek As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides ReadOnly Property CanWrite As Boolean
        Get
            Return True
        End Get
    End Property

    Public Overrides Sub Flush()
    End Sub

    Public Overrides ReadOnly Property Length As Long
        Get
            Return _buff.size()
        End Get
    End Property

    Public Overrides Property Position As Long
        Get
            Return _pos
        End Get
        Set(ByVal value As Long)
            _pos = value
        End Set
    End Property

    Public Overrides Function Read(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer) As Integer
        If buffer Is Nothing Then
            Return 0
        Else
            Dim _c As Int64
            _c = min(min(count, buffer.Length() - offset), Length() - Position())
            If _c <= 0 Then
                Return 0
            Else
                memcpy(buffer, offset, +_buff, Position(), _c)
                Return _c
            End If
        End If
    End Function

    Public Overrides Function Seek(ByVal offset As Long, ByVal origin As SeekOrigin) As Long
        If origin = SeekOrigin.Begin Then
            Position() = offset
        ElseIf origin = SeekOrigin.Current Then
            Position() += offset
        ElseIf origin = SeekOrigin.End Then
            Position() = Length() - offset
        Else
            debugassert(False, "got an invalid SeekOrigin")
            Return npos
        End If

        Return Position()
    End Function

    Public Overrides Sub SetLength(ByVal value As Long)
        _buff.size() = value
    End Sub

    Public Overrides Sub Write(ByVal buffer() As Byte, ByVal offset As Integer, ByVal count As Integer)
        _buff += New bytes(buffer, offset, count)
    End Sub

    Public Sub New()
        _buff = New bytes()
        _pos = 0
    End Sub
End Class
